#include "clientHead/epoll.h"
#include "clientHead/order_analyse.h"

void handler(int signum){
    printf("管道信号注册成功\n");
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        printf("usage: %s <IP address> <port>\n", argv[0]);
        exit(1);
    }
    
    int firstInput = 1;
    order_train_t* orderTrain = (order_train_t*)calloc(1, sizeof(order_train_t));
    order_train_t* retTrain = (order_train_t*)calloc(1, sizeof(order_train_t));
    signal(SIGPIPE, handler);
    while(1){
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        struct sockaddr_in servaddr;
        memset(&servaddr, 0, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(atoi(argv[2]));
        servaddr.sin_addr.s_addr = inet_addr(argv[1]);
        
        int epfd = epoll_create(1);
        epollAdd(epfd, STDIN_FILENO);
        epollAdd(epfd, sockfd);
        struct epoll_event readySet[2];
        
        while(1){
            printf("123\n");
            int recvFlag = 0;
            int readyNum = epoll_wait(epfd, readySet, 2, -1);
            for(int i = 0; i < readyNum; ++i){
                if(readySet[i].data.fd == STDIN_FILENO){
                    bzero(orderTrain, sizeof(order_train_t));
                    ssize_t sret = read(STDIN_FILENO, orderTrain->train_data, sizeof(orderTrain->train_data));       
                    order_judg(orderTrain->train_data, orderTrain);
                    connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
                    sendTrain(sockfd, orderTrain);
                }
                else if(readySet[i].data.fd == sockfd){
                    bzero(retTrain, sizeof(order_train_t));
                    recvTrain(sockfd, retTrain);
                    sleep(2);
                    printf("接收\n");
                    recvFlag = 1;
                    close(sockfd);
                }
            }
            if(recvFlag){
                break;
            }
        }
    }
    return 0;
}


